-- local audio = require("framework.audio")
local scheduler = require("framework.scheduler")
local audioPath = require("app.res.audio.config")
local M = class("MainScene", function()
    return display.newScene("MainScene")
end)

local imgPaths = {
	{path = "images/bg_0",weight = 359},
	{path = "images/bg_1",weight = 709},
	{path = "images/Dang",weight = 49},
	{path = "images/Default_Particle",weight = 64},
	{path = "images/guang",weight = 16},
	{path = "images/guang03",weight = 302},
	{path = "images/guang04",weight = 285},
	{path = "images/huo",weight = 83},
	{path = "images/Intro_01",weight = 72},
	{path = "images/Intro_02",weight = 561},
	{path = "images/Intro_03",weight = 536},
}

local plistPaths = {
	{path = "images/start",weight = 253},
	{path = "images/game",weight = 613},
	{path = "images/number",weight = 20},
}

local allWeight = 0
for i=1,#imgPaths do
	allWeight = allWeight + imgPaths[i].weight
end
for i=1,#plistPaths do
	allWeight = allWeight + plistPaths[i].weight
end

local oldtime = os.clock()
local updateHander = nil
local TIME = 1.5
local flashTime = 0
function M:ctor()
    self.m_imgNum = 0
    self.m_plistNum = 0
    self.m_weightVal = 0
    for i=1,#imgPaths do
    	display.addImageAsync(imgPaths[i].path..".png",function ( ... )
    		self.m_imgNum = self.m_imgNum + 1
			self:checkProgress(imgPaths[i].weight)
    	end)
    end
    for i=1,#plistPaths do
    	display.addSpriteFrames(plistPaths[i].path..".plist",plistPaths[i].path..".png",function ( ... )
    		self.m_plistNum = self.m_plistNum + 1
			self:checkProgress(plistPaths[i].weight)
    	end)
   	end
   	updateHander = scheduler.scheduleGlobal(handler(self, self.updateTime),0.1)
   	-- audio.preloadMusic(audioPath.beginBg)
   	cc.ui.UILabel.new({
            UILabelType = 2, text = "欢迎游戏", size = 64})
        :align(display.CENTER, display.cx, display.cy)
        :addTo(self)
   	math.randomseed(os.time())
   	math.random()
   	math.random()
   	math.random()
end

function M:updateTime(f)
	flashTime = flashTime + f
	if flashTime>TIME and self.m_plistNum==#plistPaths and self.m_imgNum==#imgPaths then
		scheduler.unscheduleGlobal(updateHander)
		require("app.MyApp").new():enterScene("startScene",nil,"Fade",0.8)
	end
end

function M:checkProgress(weight)
	if self.m_plistNum==#plistPaths and self.m_imgNum==#imgPaths then
		-- globalFunc.writeTabToLog({}, "开始", "log.lua", 2)
		-- require("app.MyApp").new():enterScene("startScene")
		return
	end
	self.m_weightVal = self.m_weightVal + weight
	local percent = self.m_weightVal/allWeight
	print(percent)
end

function M:onEnter()
end

function M:onExit()
end

return M
